package cn.siat.gene.service;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import cn.siat.common.core.exception.ServiceException;
import cn.siat.common.core.web.domain.AjaxResult;
import cn.siat.gene.domain.Sequence;
import cn.siat.gene.model.ConvertHistoryParam;
import cn.siat.gene.model.CutSequenceParam;
import cn.siat.gene.model.FaGffToGbParam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PyService {
    @Value("${url.py}")
    private String pyDomain;
    public void faGffToGb(FaGffToGbParam faGffToGbParam){
        String faGffToGbResultStr = HttpRequest.post(pyDomain+"/faGffToGb")
                .body(faGffToGbParam.toJsonString())
                .execute().body();
        AjaxResult jsonObject = JSON.parseObject(faGffToGbResultStr,AjaxResult.class);
        if(jsonObject.isError()){
            throw new ServiceException(jsonObject.getMsg());
        }
    }
    public List<Sequence> cutGb(CutSequenceParam cutSequenceParam,String fileName) throws JsonProcessingException {
        List<Sequence> sequenceList = new ArrayList<>();
        String cutResultStr = HttpRequest.post(pyDomain+"/cutGb")
                .body(cutSequenceParam.toJsonString())
                .execute().body();
        ObjectMapper mapper = new ObjectMapper();
        AjaxResult jsonObject = mapper.readValue(cutResultStr,AjaxResult.class);
        if(jsonObject.isError()){
            throw new ServiceException(jsonObject.getMsg());
        }
        List jsonArray = (List)jsonObject.getData();
        for (Object o : jsonArray) {
            Sequence saveSeq = mapper.readValue(mapper.writeValueAsString(o),Sequence.class);
            sequenceList.add(saveSeq.setSourceFileName(fileName));
        }
        return sequenceList;
    }
    public void convertHistory(ConvertHistoryParam convertHistoryParam){
        String result2 = HttpRequest.post(pyDomain+"/convertHistory")
                .body(convertHistoryParam.toJsonString())
                .execute().body();
        AjaxResult ajaxResult = JSON.parseObject(result2,AjaxResult.class);
        if(ajaxResult.isError()){
            throw new ServiceException(ajaxResult.getMsg());
        }
    }
}
